package cz.via.facepalm.calendar;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cz.via.facepalm.shared.CActivity;
import cz.via.facepalm.shared.CUser;
import cz.via.facepalm.shared.CUserActivity;

public class ActivityDetail extends Activity 
{
	CUser user = null;
	CUserActivity currentUA = null;
	CActivity currentA = null;
	RelativeLayout canvas = null;
	TextView target;
	ImageView cross;
	
	int fromHour,fromMinute;
	int toHour,toMinute;
	private List<CUserActivity> userActivites;
	private int index;
	
	String[] days = new String[]{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		
		CUser u = (CUser)(getIntent().getExtras().getSerializable("user"));
		if(u==null){
			throw new RuntimeException("Hacking attempt exception");
		}
		this.user = u;
		
		canvas = (RelativeLayout) findViewById(R.id.attendanceCanvas);
        target = (TextView) findViewById(R.id.target);
        cross = (ImageView) findViewById(R.id.cross);
		
        Button confirm  = (Button) findViewById(R.id.confirm_attendance_btn);
        confirm.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{		
				final ProgressDialog progress = ProgressDialog.show(ActivityDetail.this, "",
						"Confirming",true);
				ServerComunicator.saveOrChangeAttendance(currentUA, new DoneCallback<Void>() {
					@Override
					public void done(Void result) {						
						ActivityDetail.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								progress.dismiss();
							}
						});
					}
				});
			}
		});
        
        Button mainMenuBtn = (Button) findViewById(R.id.detail_main_menu);  
	    registerForContextMenu(mainMenuBtn);
        
        Button othersBtn = (Button) findViewById(R.id.show_others_btn);
		othersBtn.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{	
				Intent intent = new Intent(ActivityDetail.this,
						OthersAttendanceActivity.class);
		    	Bundle exchangeData = new Bundle();							
		    	exchangeData.putSerializable("user", ActivityDetail.this.user);
		    	exchangeData.putSerializable("cactivity", ActivityDetail.this.currentA);
				intent.putExtras(exchangeData);
				startActivity(intent);				
			}
		});
        
		ServerComunicator.listUserActivities(user.getId(), new DoneCallback<List<CUserActivity>>(){
			@Override
			public void done(List<CUserActivity> result) {
				userActivites = result;
				
				if(result.size() == 0) 
				{
					ActivityDetail.this.runOnUiThread(new Runnable() {
				        public void run() {
				        	AlertDialog.Builder builder = new AlertDialog.Builder(ActivityDetail.this);
							builder.setMessage("You have no subscribed activity")
							       .setCancelable(false)
							       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							           public void onClick(DialogInterface dialog, int id) {
							        	   
							        	   Intent intent = new Intent(ActivityDetail.this,
													CalendarActivity.class);
							        	   Bundle exchangeData = new Bundle();							
							        	   exchangeData.putSerializable("user", ActivityDetail.this.user);			    	
							        	   intent.putExtras(exchangeData);
							        	   startActivity(intent);
							        	   
							               //ActivityDetail.this.finish();
							           }
							       });
							AlertDialog alert = builder.create();
							alert.show();
				        }
				    });
				}
				else{			
					Long goAt = (getIntent().getExtras().getLong("activityId"));
					index = 0;
					for(int i=0;i<userActivites.size();i++)					
					{
						if(userActivites.get(i).getIdActivity().getId()==goAt)
						{
							index = i;
							break;
						}
					}					
					onActivityIndexChange();
				}
			}
		});						
        canvas.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{			      											
					float x = event.getX();
	            	float y = event.getY();	                        
	            	float yesno = x/v.getWidth();
	            	float time = y/v.getHeight();	            	
	            	setAttendanceView(yesno, time);            		            		            	
				return true;
			}
		});
        
        Button prevBtn = (Button) findViewById(R.id.srac_prev);
        prevBtn.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				if(index < userActivites.size() -1){
					index++;
					onActivityIndexChange();
				}
			}
		});
        
        Button nextBtn = (Button) findViewById(R.id.srac_next);
        nextBtn.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				if(index > 0){
					index--;
					onActivityIndexChange();
				}
			}
		});
        
	}
	
	protected void onActivityIndexChange() {
		currentUA = userActivites.get(index);				
		if(currentUA == null) {
			System.out.println("List of subscribed activities is empty");
			return;
		}
		currentA = currentUA.getIdActivity();
		if(currentA == null) {
			System.out.println("Activity of current UserActivity is empty");
			return;
		}
		
		//Update view in synchronized thread
		ActivityDetail.this.runOnUiThread(new Runnable() {
	        public void run() 
	        {			        	
	        	TextView name = (TextView) findViewById(R.id.activity_name);
	        	name.setText(currentA.getName());
	        	
	        	TextView from = (TextView) findViewById(R.id.from_time);
	        	from.setText(ActivityHelper.getStartTime(currentA));
	        	TextView to = (TextView) findViewById(R.id.to_time);
	        	to.setText(ActivityHelper.getFinishTime(currentA));			        				        
	        	TextView date = (TextView) findViewById(R.id.activity_date);			        	
	        	date.setText( days[ActivityHelper.getWeeklyDay(currentA)%7]+" "+
	        				  from.getText()+" - "+to.getText());
	        	setAttendanceView(currentUA.getPercentComming()*0.01f, currentUA.getPercentLate()*0.01f);
	        	
	        }
	    });
	}
	
	protected void setAttendanceView(float yesno, float time)
	{		
		float x = yesno * canvas.getWidth();
		float y = time * canvas.getHeight();
		
		int c = Color.rgb((int)(yesno*255), (int)((1-yesno)*255), 0);	            	
    	canvas.setBackgroundColor(c);

    	MarginLayoutParams marginParams = new MarginLayoutParams(cross.getLayoutParams());
        marginParams.setMargins((int)x-(int)(cross.getWidth()*0.5),
        		(int)(y-cross.getHeight()*0.5), 0, 0);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
        cross.setLayoutParams(layoutParams);
    	                       
        
    	target.setText( ((int)(yesno*100))+"%, "+ActivityHelper.getTimeWithPct(currentA, time));
    	
    	currentUA.setPercentComming((int)(yesno*100));
    	currentUA.setPercentLate((int)(time*100));
	}
	
	@Override  
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) 
    {  
    	super.onCreateContextMenu(menu, v, menuInfo);  
	    menu.setHeaderTitle("Actions");  
	    menu.add(0, v.getId(), 0, "Activities list");  	     
    }
	
	@Override  
	public boolean onContextItemSelected(MenuItem item) 
	{  
	    if(item.getTitle()=="Activities list"){
	    	Intent intent = new Intent(ActivityDetail.this,
					CalendarActivity.class);
	    	Bundle credentials = new Bundle();							
			credentials.putSerializable("user", this.user);
			intent.putExtras(credentials);
			startActivity(intent);
	    }  
	    
	    else return false;  
	    return true;  
	}  
		
}